import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../../AppConfig/Config.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/NoLoadingPostApi.dart';

class InvitingDrivers extends StatefulWidget {
  const InvitingDrivers({super.key, required this.fleetMap});
  final Map fleetMap;
  @override
  State<InvitingDrivers> createState() => _InvitingDriversState();
}

class _InvitingDriversState extends State<InvitingDrivers> {
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  Map driverMap={};
  String driverId="";

  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    super.initState();

  }

  void searchDriverAction(String drvPhoneNum) async {
    driverId=(await PhoneNumManager.getPhone())!;
    print(driverId);
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/driver/user/getUserByPhone', // 您的API端点key
      {"phoneNum":drvPhoneNum}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          driverMap=responseData['data'];
        });
      },
    );

  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color.fromRGBO(248, 248, 248, 1),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text("邀请司机",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300),),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
        body:  Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [MyColors.themeColor,MyColors.backgreyColor, MyColors.backgreyColor,MyColors.backgreyColor], // 渐变颜色数组
                begin: Alignment.topCenter, // 渐变开始的位置
                end: Alignment.bottomCenter, // 渐变结束的位置
              ),

            ),
            child:ListView(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 10.h),
                  width: screenSize.width ,
                  child: Column(
                    children: [
                      Row(
                        children: [
                          SizedBox(width: 20.w,),
                          Container(
                            width: 60.w,
                            height: 60.h,
                            child:  widget.fleetMap['avatarPath']!=null&&widget.fleetMap['avatarPath']!=""?
                            CircleAvatar(
                              radius: 15,
                              backgroundImage: NetworkImage(MyServiceUrl.imgHeader +widget.fleetMap['avatarPath']),
                            )
                                :  CircleAvatar(
                              radius: 15,
                              backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                            ),
                          ),
                          SizedBox(width: 8.w,),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(widget.fleetMap['name'],style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 16.sp),),
                              if(widget.fleetMap['description']!=null)
                                Text(widget.fleetMap['description'].toString(),style: TextStyle(color: Colors.white,fontWeight: FontWeight.w600,fontSize: 16.sp),),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    children: [
                      Text("邀请加入",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                      SizedBox(height: 10.h,),
                      Container(
                        height: 50.h,
                        child: BrnSearchText(
                          autoFocus:false,
                          focusNode: focusNode,
                          controller: textController,
                          searchController: scontroller..isActionShow = false,
                          outSideColor:Colors.white,
                          innerColor:MyColors.backgreyColor,
                          textInputType:TextInputType.number,
                          borderRadius:BorderRadius.all(const Radius.circular(10.0)),
                          hintText:"输入司机手机号码",
                          onTextClear: () {
                            debugPrint('sss');
                            return false;
                          },
                          onActionTap: () {
                            scontroller.isClearShow = false;
                            scontroller.isActionShow = false;
                            focusNode.unfocus();
                          },
                          onTextCommit: (text) {
                          },
                          onTextChange: (text) {
                            if(text.length==11) {
                              searchDriverAction(text);
                            }
                          },
                        ),
                      ),
                      if(driverMap.isNotEmpty)
                        Container(
                          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 20.h),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 40.w,
                                      height: 40.h,
                                      child:  driverMap['avatarPath']!=null&&driverMap['avatarPath']!=""?
                                      CircleAvatar(
                                        radius: 15,
                                        backgroundImage: NetworkImage(MyServiceUrl.imgHeader +driverMap['avatarPath']),
                                      )
                                          :  CircleAvatar(
                                        radius: 15,
                                        backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                                      ),
                                    ),
                                    SizedBox(width: 8.w,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(driverMap['realName'].toString(),style: TextStyle(color: Colors.black,fontSize: 15.sp),),
                                        Text(driverMap['phoneNum'].toString(),style: TextStyle(color: Colors.black,fontSize: 13.sp),)
                                      ],
                                    )
                                  ],
                                ),
                                SizedBox(height: 10.h,),
                                if(driverMap['vehicleNum']!=""&&driverMap['vehicleNum']!=null)
                                Text(driverMap['vehicleNum'].toString(),style: TextStyle(color: Colors.black,fontSize: 15.sp),),
                                Row(
                                  children: [
                                    if(driverMap['vehicleLength']!=""&&driverMap['vehicleLength']!=null)
                                      Text(driverMap['vehicleLength'].toString(),style: TextStyle(color: Colors.black,fontSize: 15.sp),),
                                    if(driverMap['vehicleModel']!=""&&driverMap['vehicleModel']!=null)
                                      Text(driverMap['vehicleModel'].toString(),style: TextStyle(color: Colors.black,fontSize: 15.sp),),
                                  ],
                                ),
                                Row(
                                  children: [
                                    (driverMap['vehicleDrivingLicenseStatus']==0||driverMap['vehicleDrivingLicenseStatus']==3)?
                                    Icon(Icons.
                                    error_outline,color: Colors.red,size: 12,)
                                        :driverMap['vehicleDrivingLicenseStatus']==1?
                                    Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                        :
                                    Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),
                                    Text("行驶证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                    SizedBox(width: 8.w,),
                                    (driverMap['roadTransportCertificateStatus']==0||driverMap['roadTransportCertificateStatus']==3)?
                                    Icon(Icons.
                                    error_outline,color: Colors.red,size: 12,)
                                        :driverMap['roadTransportCertificateStatus']==1?
                                    Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                        :
                                    Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),
                                    Text("道路运输证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                  ],
                                ),
                              ],
                            ),
                            driverMap['phoneNum']==driverId?
                                Text("不能邀请本人",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),)
                            :driverMap['personalStatus']!=2?
                            Text("司机未认证",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),):
                            GestureDetector(
                              child:    Column(
                                children: [
                                  Icon(Icons.person_add,color: MyColors.themeColor,),
                                  Text("邀请",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                                ],
                              ),
                              onTap: (){
                                showDialog(
                                  barrierDismissible: false,
                                  context: context,
                                  builder: (BuildContext context) {
                                    return InvitingD(dataMap: driverMap,);
                                  },
                                );
                                // showDialog(
                                //     context: context,
                                //     builder: (BuildContext context) {
                                //       return InvitingD();
                                //     }
                                // );
                              },
                            )

                          ],
                          )

                        )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 15.w,top: 10.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("邀请说明",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      SizedBox(height: 2.h,),
                      Text("1、输入邀请人手机号，获取用户信息",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                      SizedBox(height: 2.h,),
                      Text("2、确认用户信息，点击获取验证码",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                      SizedBox(height: 2.h,),
                      Text("3、输入邀请人手机验证码，确认邀请",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                    ],
                  ),
                )
              ],
            ),
        ),

    );
  }
}
class InvitingD extends StatefulWidget {
  const InvitingD({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<InvitingD> createState() => _InvitingDState();
}

class _InvitingDState extends State<InvitingD> {
  late Timer _timer;
  int curentTimer=0;
  bool isTimerRunning = false;
  String smsCode="";
  String validCodeReqNo="";
  void startTimer() {
    setState(() {
      curentTimer = 60;
      isTimerRunning = true; // 设置定时器正在运行
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        curentTimer--;
        if (curentTimer == 0) {
          _timer.cancel();
          isTimerRunning = false; // 定时器结束后设置为非运行状态

          if (mounted) {
            setState(() {}); // 刷新状态以使按钮可点击
          }
        }
        if (!mounted) {
          _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
        }
        setState(() {});
      });
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  void sendPhoneCodeAct(){
    NoLoadingApiManager.postData(
      context,
      "api/auth/sms/sendPhoneValidCode",
      {'phone':widget.dataMap['phoneNum'],"clientType":"DRIVER","codeType":"FLEET_BIND_DRIVER"},
          (responseData)  {
        setState(() {
          startTimer();
          validCodeReqNo=responseData['data']['validCodeReqNo'];
          BrnToast.show("验证码发送成功", context);
        });

      },
    );
  }
  void sureInvitAct(){
    NoLoadingApiManager.postData(
      context,
      "api/auth/sms/checkPhoneValidCode",
      {'phone':widget.dataMap['phoneNum'],"clientType":"DRIVER","codeType":"FLEET_BIND_DRIVER","validCode":smsCode,"validCodeReqNo":validCodeReqNo},
          (responseData)  {
        setState(() {
          startTimer();
          BrnToast.show("验证码发送成功", context);
        });

      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return BrnDialog(
          titleText: "确定邀请司机",
          warningWidget:Container(
            margin: EdgeInsets.only(top: 20.h),
            child:
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "验证码",
                  style: TextStyle(color: MyColors.textColor, fontSize: 14.sp),
                ),
                SizedBox(width: 10.w),
                Container(
                  width: 100.w,
                  height: 30.h,
                  decoration: BoxDecoration(
                      color: MyColors.backgreyColor,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: '请输入验证码',
                      hintStyle:
                      TextStyle(fontSize: 13.sp, color: MyColors.hintColor),
                      filled: true,
                      fillColor: MyColors.backgreyColor,
                      border: InputBorder.none,
                    ),
                    keyboardType: TextInputType.number,
                    textAlign: TextAlign.left,
                    style: TextStyle(color: Colors.black, fontSize: 13.sp),
                    onChanged: (value) {
                      setState(() {
                        smsCode=value;
                        // 在这里可以添加文本改变时的逻辑
                      });
                    },
                  ),
                ),
                SizedBox(width: 8.w,),
                GestureDetector(
                  onTap: (){
                    if(curentTimer==0) {
                        sendPhoneCodeAct();
                    }

                  },
                  child: curentTimer>0?  Text(curentTimer.toString() +"s",style: TextStyle(color: MyColors.hintColor,fontSize: 12.sp),):
               Text(
                    "获取验证码",
                    style: TextStyle(color: MyColors.themeColor, fontSize: 12.sp),
                  ),
                )
              ],
            ),
          ) ,
          actionsWidget: [
            TextButton(
              onPressed: () {
                _timer.cancel();
                Navigator.pop(context);
              },
              child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
            ),
            TextButton(
              onPressed: () {
              sureInvitAct();
              },
              child: Text("确认邀请",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
            ),
          ],
        );

  }
}
